<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Api\V1;

use Think\Exception;

class DecodeMobile
{
    public $login = true; //是否需要登录才能访问该接口
    public $title = "解码手机号";
    public $group = '个人中心';
    public $desc = "";

    public $input = [
        'encrytedData' => 'required;label=encrytedData',
        'session_key' => 'required;label=session_key',
        'iv' => 'required;label=iv',
    ];

    public $output = [
        'data' => [
            'phoneNumber' => 'label=用户绑定的手机号（国外手机号会有区号）;',
            'purePhoneNumber' => 'label=没有区号的手机号;',
            'countryCode' => 'label=区号;',
        ]
    ];

    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;

    public function run($param, $uid, $login_info)
    {
        $appid = 'wx899ad8ca0a9fd507';
        $sessionKey = $param['session_key'];
        $encryptedData= $param['encrytedData'];
        $iv = $param['iv'];

        $errCode = self::decryptData($encryptedData, $iv, $data, $sessionKey, $appid);
        if ($errCode == 0) {
            return ['code' => 1, 'data' => json_decode($data, true)];
        } else {
            throw new Exception('解码失败errCode');
        }
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $encryptedData, $iv, &$data, $sessionKey, $appid)
    {

        if (strlen($sessionKey) != 24) {
            return self::$IllegalAesKey;
        }
        $aesKey=base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return self::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return self::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $appid )
        {
            return self::$IllegalBuffer;
        }
        $data = $result;
        return self::$OK;
    }
}